package com.common.android.utils.smiley;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.Browser;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.text.style.URLSpan;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.common.android.utils.DisplayUtil;
import com.common.android.utils.StringUtils;
import com.common.android.utils.UrlUtils;
import com.common.android.utils.db.CommonDaoFactory;
import com.nd.android.u.allcommon.R;
import com.product.android.business.ApplicationVariable;
import com.product.android.utils.LogUtils;

/**
 * 解析表情类
 * @author Administrator
 */
@SuppressLint("UseSparseArrays")
public final class Smileyhelper {
	public static final int HISTORY=0;
	public static final int NORMAL=1;
	public static final int EMOJI=2;
	public static final int COS = 3;
	public static final int CAT=4;
	public static final int SIZE_CAT=8;
	public static final int SIZE_OTHER=21;
	public static final int COLUMNS_CAT=4;
	public static final int COLUMNS_OTHER=7;
	public static final int DEL_ID=993;
	public static final int UNKOWN_ID=2157;
	private int mCatSize=0;
	private int mCosSize = 0;
	private int mEmojiSize=0;
	private static final int NOT_FOUND=-2;
	private final int[] EMOJI_INTERZONE={126980,128709};
	private final int SP_VALUE=169;
	private final int SP_VALUE1=174;
	private int[] EMOJI_VALUES={9728,
			9748,
			9749,
			9757,
			9786,
			9824,
			9889,
			9917,
			9918,
			9962,
			9971,
			9973,
			9992,
			9994,
			9995,
			9996,
			10060,
			10068,
			10069,
			11088,
			11093
	};
	private static Smileyhelper instance;
	private Map<Integer, Smiley> smileyMap;
	private List<Smiley> mSmileyAllList=new ArrayList<Smiley>();
	private List<Smiley> mHistoryList=new ArrayList<Smiley>();
	private List<Smiley> mNormalList=new ArrayList<Smiley>();
	private List<Smiley> mCatList=new ArrayList<Smiley>();
	private List<Smiley> mEmojiList=new ArrayList<Smiley>();
	private List<Smiley> mCosList = new ArrayList<Smiley>();
	private List<Smiley> mNoResourceSmiley=new ArrayList<Smiley>();
	private List<Smiley> mDefaultList = new ArrayList<Smiley>();
	private List<Smiley> mCoolMonkeyList = new ArrayList<Smiley>();
	private List<Smiley> mGrapeManList = new ArrayList<Smiley>();
	private HashMap<String, Integer> mTipIdMaps=new HashMap<String, Integer>();
	private HashMap<Integer, Smiley> mUnicodeSmileyMap=new HashMap<Integer, Smiley>();
	/**是否打开系统自带浏览器*/
	//FRI HYK修改 by明星App
	private boolean mIsOpenSysBrowser = false;
	
	public static Smileyhelper getInstance() {
        if (instance == null) {
            instance = new Smileyhelper();
            Log.e("HYK", "Smileyhelper instance");
        }
        return instance;
	}


    public void clearInstance() {
        instance = null;
    }

    public Smileyhelper() {
		for (int i=0,count=SmileyValueArray.NORMAL_ID.length;i<count;i++){
			Smiley smiley=new Smiley();
			smiley.id=SmileyValueArray.NORMAL_ID[i];
			smiley.name=SmileyValueArray.NORMAL_NAME[i];
			smiley.tip=SmileyValueArray.NORMAL_TIP[i];
			mNormalList.add(smiley);
		}
		mEmojiSize=SmileyValueArray.EMOJI_ID.length;
		for (int i=0;i<mEmojiSize;i++){
			Smiley smiley=new Smiley();
			smiley.id=SmileyValueArray.EMOJI_ID[i];
			smiley.name=SmileyValueArray.EMOJI_NAME[i];
			smiley.tip=SmileyValueArray.EMOJI_TIP[i];
			smiley.unicode=SmileyValueArray.EMOJI_UNICODE[i];
			smiley.utf8Code=SmileyValueArray.EMOJI_HEX[i];
			mEmojiList.add(smiley);
			mUnicodeSmileyMap.put(smiley.unicode, smiley);
		}
		mCosSize = SmileyValueArray.COS_ID.length;
        for(int i = 0; i <mCosSize; i++){
            Smiley smiley = new Smiley();
            smiley.id = SmileyValueArray.COS_ID[i];
            smiley.name = SmileyValueArray.COS_NAME[i];
            smiley.gifName = SmileyValueArray.COS_GIF_NAME[i];
            smiley.tip = SmileyValueArray.COS_TIP[i];
            mCosList.add(smiley);
        }
		mCatSize=SmileyValueArray.CAT_ID.length;
		for (int i=0;i<mCatSize;i++){
			Smiley smiley=new Smiley();
			smiley.id=SmileyValueArray.CAT_ID[i];
			smiley.name=SmileyValueArray.CAT_NAME[i];
			smiley.tip=SmileyValueArray.CAT_TIP[i];
			smiley.gifName=SmileyValueArray.CAT_GIF_NAME[i];
			mCatList.add(smiley);
		}
		String[] noResourceTips=ApplicationVariable.INSTANCE.applicationContext.getResources().getStringArray(R.array.no_resource_smiley_tip);
		for (int i=0,count=SmileyValueArray.NO_RESOURCE_ID.length;i<count;i++){
			Smiley smiley=new Smiley();
			smiley.id=SmileyValueArray.NO_RESOURCE_ID[i];
			smiley.name=SmileyValueArray.NO_RESOURCE_NAME[i];
			smiley.tip=noResourceTips[i];
			mNoResourceSmiley.add(smiley);
		}
		
		for (int i=0,count=SmileyValueArray.DEFAULT_ID.length;i<count;i++){
			Smiley smiley=new Smiley();
			smiley.id=SmileyValueArray.DEFAULT_ID[i];
			smiley.name=SmileyValueArray.DEFAULT_NAME[i];
			smiley.tip=SmileyValueArray.DEFAULT_TIP[i];
			mDefaultList.add(smiley);
		}
		for (int i=0,count=SmileyValueArray.COOLMONKEY_ID.length;i<count;i++){
			Smiley smiley=new Smiley();
			smiley.id=SmileyValueArray.COOLMONKEY_ID[i];
			smiley.name=SmileyValueArray.COOLMONKEY_NAME[i];
			smiley.tip=SmileyValueArray.COOLMONKEY_TIP[i];
			mCoolMonkeyList.add(smiley);
		}
		for (int i=0,count=SmileyValueArray.GRAPEMAN_ID.length;i<count;i++){
			Smiley smiley=new Smiley();
			smiley.id=SmileyValueArray.GRAPEMAN_ID[i];
			smiley.name=SmileyValueArray.GRAPEMAN_NAME[i];
			smiley.tip=SmileyValueArray.GRAPEMAN_TIP[i];
			mGrapeManList.add(smiley);
		}
		mSmileyAllList.addAll(mCatList);
		mSmileyAllList.addAll(mEmojiList);
		mSmileyAllList.addAll(mCosList);
		mSmileyAllList.addAll(mNormalList);
		mSmileyAllList.addAll(mNoResourceSmiley);
		mSmileyAllList.addAll(mDefaultList);
		mSmileyAllList.addAll(mCoolMonkeyList);
		mSmileyAllList.addAll(mGrapeManList);
		smileyMap = initSmileyMap();
		initMap();
		replaceDelSmiley();
	}
	
	private void initHistorySmiley(){
		mHistoryList=CommonDaoFactory.getInstance().getSmileyHistoryDao().getSmileyList();
	}
	
	private void replaceDelSmiley(){
		if (mSmileyAllList!=null){
			for (Smiley smiley:mSmileyAllList){
				if (smiley.name.equals("smiley/smiley_del.png")){
					smiley.id=(DEL_ID);
				}
			}
		}
	}
	
	private void initMap(){
		for(Smiley smiley:mSmileyAllList){
			smileyMap.put(smiley.id, smiley);
		}
	}
	
	public Smiley getSmiley(int id){
		if (id<0){
			return null;
		}
		if(smileyMap!=null&&smileyMap.containsKey(id)){
			return smileyMap.get(id);
		}
		else return null;
	}
	
	/**
	 * 设置表情
	 */
	public void setSmiley(Context context, ImageView imgView, String name) {
		Bitmap bmp=getImageFromAssetsFile(context,name);
		imgView.setImageBitmap(bmp);
	}

	
	/**
	 * 根据id获取表情的图片
	 * <br>Created 2014-7-18 下午3:33:13
	 * @param context
	 * @param id
	 * @return
	 * @author       cb
	*/
	public Drawable getSmileyById(Context context,int id){
		Smiley smiley=getSmiley(id);
		if (smiley==null){
			//未取到表情，使用默认的未知表情图标
			id=UNKOWN_ID;
			smiley=getSmiley(id);
		}
		if (smiley==null){
			return null;
		}
		Bitmap bmp= getImageFromAssetsFile(context, smiley.name);
		if (bmp==null){
			return null;
		}
		return new BitmapDrawable(context.getResources(), bmp);
	}
	
	/**
     * 从Assets中读取图片
     */
	public Bitmap getImageFromAssetsFile(Context context,String fileName) {
		if (TextUtils.isEmpty(fileName)){
			return null;
		}
		Bitmap image = null;
		AssetManager am = context.getResources().getAssets();
		try {
			InputStream is = am.open(fileName);
			image = BitmapFactory.decodeStream(is);
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return image;
	}

	
	public int getSmileyGifResidById(int id){
		Smiley smiley=getSmiley(id);
		if (smiley!=null){
			String appName=ApplicationVariable.INSTANCE.applicationContext.getPackageName();
			int resId = ApplicationVariable.INSTANCE.applicationContext.getResources().getIdentifier(
					smiley.gifName, "drawable",appName);
			return resId;
		}
		return 0;
	}

	public SpannableString getHtml(String str){
		SpannableString spannable = new SpannableString(str);
		return getHtml(spannable,str,true);
	}
	
	public SpannableString getHtml(SpannableString span,String str,boolean bool){
		if (StringUtils.isEmpty(str))
			return span;
		Matcher matcher = UrlUtils.WEB_URL.matcher(str);
		String group;
		int start = 0;
		int end = 0;
		int len=span.length();
		while (matcher.find()){
			start = matcher.start();
			end = matcher.end();
			group = UrlUtils.makeUrl(matcher.group());
			if(!bool){
				span.setSpan(new MyUrlSpan(group), start, Math.min(end,len), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
			}
			else{
				if(group.contains("?")){
					span.setSpan(new MyUrlSpan(group+"&sid="+ApplicationVariable.INSTANCE.getIUser().getSid()), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
				}
				else{
					span.setSpan(new MyUrlSpan(group+"?sid="+ApplicationVariable.INSTANCE.getIUser().getSid()), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
				}
			}
		}
		return span;
	}
	
	public List<String> getUrls(String str) {
		List<String> list = new ArrayList<String>();
		Matcher matcher = UrlUtils.WEB_URL.matcher(str);
		while (matcher.find()){
			list.add(matcher.group());
		}
		return list;
	}
	
	public Map<Integer, Smiley> initSmileyMap() {
		Map<Integer, Smiley> smileyMap = null;
		smileyMap = new HashMap<Integer, Smiley>();
		if (mSmileyAllList == null || mSmileyAllList.size() == 0) {
			return smileyMap;
		}
		for (Smiley smiley : mSmileyAllList) {
			smileyMap.put(smiley.id, smiley);
			mTipIdMaps.put(smiley.tip, smiley.id);
		}
		return smileyMap;
	}

	public Map<Integer, Smiley> getSmileyMap() {
		return smileyMap;
	}
	
	public void refreshHistorySmiley(){
		initHistorySmiley();
	}
	
	public List<Smiley> getSmileyList(int type){
		switch (type) {
		case EMOJI:
			return mEmojiList;
		case COS:
			return mCosList;
		case CAT:
			return mCatList;
		case HISTORY:
			if (mHistoryList==null || mHistoryList.size()==0){
				initHistorySmiley();
			}
			return mHistoryList;
		case NORMAL:
			return mNormalList;
		default:
			
		}
		return null;
	}

	public boolean isContainSimleyId(int smileyId){
		if(smileyMap.containsKey(smileyId)){
			return true;
		}
		return false;
	}
	
	/**
	 * @n<b>函数名称</b>     :getByUnicode
	 * @brief　根据UNICODE值获取对应的表情ID
	 * @see
	 * @since    Ver 1.2
	 * @param  @param unicode
	 * @param  @return
	 * @return int
	 * @<b>作者</b>          :  cb
	 * @<b>创建时间</b>      :  2013-10-29下午2:05:53      
	*/
	public int getIdByUnicode(int unicode){
		if (mUnicodeSmileyMap.containsKey(unicode)){
			Smiley smiley=mUnicodeSmileyMap.get(unicode);
			return smiley.id;
		}
		return UNKOWN_ID;
	}
	
	/**
	 * @n<b>函数名称</b>     :isCatID
	 * @brief 确认一个表情的ID是否是猫先生的ID
	 * @see
	 * @since    Ver 1.2
	 * @param  @param id
	 * @param  @return
	 * @return boolean
	 * @<b>作者</b>          :  cb
	 * @<b>创建时间</b>      :  2013-10-29下午2:05:39      
	*/
	public boolean isCatID(int id){
		return (id>=SmileyValueArray.CAT_ID[0] && id<=SmileyValueArray.CAT_ID[mCatSize-1]);
	}
	
	/**
	 * 确认一个表情的ID是否是英魂之刃的ID
	 * <br>Created 2014-9-2 下午2:57:43
	 * @param id
	 * @return
	 * @author       CYP
	*/
	public boolean isCosID(int id){
	    return (id >= SmileyValueArray.COS_ID[0] && id <= SmileyValueArray.COS_ID[mCosSize - 1]); 
	}
	
	/**
	 * @n<b>函数名称</b>     :isEmoji
	 * @brief　确认一个表情的ID是否是EMOJI
	 * @see
	 * @since    Ver 1.2
	 * @param  @param id
	 * @param  @return
	 * @return boolean
	 * @<b>作者</b>          :  cb
	 * @<b>创建时间</b>      :  2013-10-29下午2:05:21      
	*/
	public boolean isEmoji(int id){
		return (id>=SmileyValueArray.EMOJI_ID[0] && id<=SmileyValueArray.EMOJI_ID[mEmojiSize-1]);
	}
	
	/**
	 * @n<b>函数名称</b>     :getSmileyIdByTip
	 * @brief　根据tip查找对应的表情的ID
	 * @see
	 * @since    Ver 1.2
	 * @param  @param tip
	 * @param  @return
	 * @return int
	 * @<b>作者</b>          :  cb
	 * @<b>创建时间</b>      :  2013-10-29下午2:05:11      
	*/
	public int getSmileyIdByTip(String tip){
		if (mTipIdMaps.containsKey(tip)){
			return mTipIdMaps.get(tip);
		}
		LogUtils.d("debug", "can't find [+"+tip+"]");
		for (Smiley smiley:mSmileyAllList){
			if (!TextUtils.isEmpty(smiley.tip)){
				if (smiley.tip.equals(tip)){
					return smiley.id;
				}	
			}
		}
		return NOT_FOUND;
	}
	
	/**
	 * @n<b>函数名称</b>     :seekEmoji
	 * @brief　查找一个字符串里的EMOJI表情
	 * @see
	 * @since    Ver 1.2
	 * @param  @param input
	 * @param  @param type
	 * @param  @return
	 * @return String
	 * @<b>作者</b>          :  cb
	 * @<b>创建时间</b>      :  2013-10-29下午2:05:00      
	*/
	public String seekEmoji(String input,int type){
		String result="";
		char[] ach = input.toCharArray();  // a char array copied from str
	    int len = ach.length;            // the length of ach
	    int[] acp = new int[Character.codePointCount(ach, 0, len)];
	    int j = 0;                       // an index for acp
	    String imgStart=Smiley.getStartString(type);
	    String imgEnd=Smiley.getEndString(type);
	    String smileyCode;
	    for (int i = 0, cp; i < len; i += Character.charCount(cp)) {
	    	//取整个字符的UNICODE值
	        cp = Character.codePointAt(ach, i);
	        acp[j++] = cp;
	        
	        //判断这个字符的UNICODE值是不是EMOJI的UNICODE，如果是则取出对应的ID，如果不是则返回-1
	        int id=checkEmoji(cp);
	        
	        //取该字符共占多少个字节
	        int count=Character.charCount(cp);
	        if (id!=-1){
	        	//如果是EMOJI表情，如果是聊天界面使用，替换成&<img>id<img>&；如果是微博使用替换成[tip]
	        	smileyCode=id+"";
	        	if (type!=Smiley.TYPE_CHAT){
	        		Smiley smiley=Smileyhelper.getInstance().getSmiley(id);
	        		if (smiley!=null){
	        			smileyCode=smiley.tip;
	        		}
	        	}
        		result+=imgStart+smileyCode+imgEnd;
	        }else{
	        	//不是EMOJI表情，直接返回原字符
	        	result+=input.substring(i,i+count);
	        }
	    }
	    return result;
	}
	
	/**
     * 把形如[开心]这样的表情表示字符换成&<img>0<img>&这种形式
     * 
     * <br>Created 2014-9-29 下午2:15:43
     * @param srcStr [开心]形式的表情
     * @param type 表情类型
     * @return &<img>0<img>&的表情
     * @author       caocr
     */
    public String convertMXSmileyToIMSmiley(String srcStr, int type) {
        if (TextUtils.isEmpty(srcStr)) {
            return srcStr;
        }
        String imgStart = Smiley.getStartString(type);
        String imgEnd = Smiley.getEndString(type);
        StringBuffer temp = new StringBuffer();
        String src = seekEmoji(srcStr, type); // 将字符串中含有的emoji表情转化为形如[开心]这样的表情表示字符
        String[] slices = src.split("\\" + imgStart);
        int len = slices.length;

        if (len <= 1) {
            return src;
        }
        temp.append(slices[0]);
        for (int i = 1; i < len; i = i + 1) {
            String slice = slices[i];
            int index = slice.indexOf(imgEnd);
            if (index <= 0) {
                // 未匹配到结束标识或者未带ID(即[]这样，中间没有Tip)
                temp.append(imgStart);
                temp.append(slice);
                continue;
            }
            String smileyStr = slice.substring(0, index);
            int id = getIdBySmileyStr(smileyStr);
            if (id > 0) {
                // 找到对应的smiley
                temp.append("&<img>");
                temp.append(id);
                temp.append("<img>&");
                temp.append(slice.substring(index + imgEnd.length()));
            } else {
                temp.append(imgStart);
                temp.append(slice);
            }
        }

        return temp.toString();
    }
	
	/**
	 * @n<b>函数名称</b>     :checkEmoji
	 * @brief 判断一个整数值（实际上某个字符的unicode的十进制值）是否是emoji表情的unicode值
	 * @see
	 * @since    Ver 1.2
	 * @param  @param cp
	 * @param  @return
	 * @return int
	 * @<b>作者</b>          :  cb
	 * @<b>创建时间</b>      :  2013-10-29下午2:03:34      
	*/
	private int checkEmoji(int cp){
		if (cp==SP_VALUE || cp==SP_VALUE1){
			//是特殊的emoji表情（本地不支持，显示?）
			return Smileyhelper.UNKOWN_ID;
		}
		if (cp>=EMOJI_INTERZONE[0] && cp<=EMOJI_INTERZONE[1]){
			//落在EMOJI的区间内
			return Smileyhelper.getInstance().getIdByUnicode(cp);
		}
		int len=EMOJI_VALUES.length;
		if (cp>=EMOJI_VALUES[0] && cp<=EMOJI_VALUES[len-1]){
			//属于特定的一些表情
			for (int i=0;i<len;i++){
				if (cp==EMOJI_VALUES[i]){
					return Smileyhelper.getInstance().getIdByUnicode(cp);
				}
			}
		}
		return -1;
	}
	
	
	/**
	 * 
	 * ClassName:EMOJI
	 * Function: 用于设置ImageSpan用的信息
	 * Reason:	 TODO ADD REASON
	 * 
	 * @author   huangszh		
	 * @version  Smileyhelper
	 * @since    Ver 1.1
	 * @Date	 2014	2014-3-6		下午2:18:28
	 *
	 * @see
	 */
	public class EMOJI{
		public int start; // 原文本设置ImageSpan的起始位置
		public int end;   // 原文本设置ImageSpan的结束位置
		public int local_smiley_id; // emoji表情对应的本地定义的图片id
		
		public EMOJI(int start,int end,int smiley_id){
			this.start = start;
			this.end = end;
			this.local_smiley_id = smiley_id;
		}
	}
	
	/**
	 * 
	 * @n<b>函数名称</b>     :seekEmojiArray
	 * @brief	查找文本内的emoji
	 * @see
	 * @since    Ver 1.1
	 * @param  @param input	
	 * @param  @param begin	input在原文本的起始位置
	 * @param  @return
	 * @return ArrayList<EMOJI>
	 * @<b>作者</b>          :  huangszh
	 * @<b>创建时间</b>      :  2014-3-6下午2:18:20
	 */
	private ArrayList<EMOJI> seekEmojiArray(String input,int begin){
		ArrayList<EMOJI> emojis = new ArrayList<Smileyhelper.EMOJI>();
		char[] ach = input.toCharArray();  // a char array copied from str
	    int len = ach.length;            // the length of ach
	    EMOJI emoji ;
	    for (int i = 0, cp; i < len;) {
	    	//取整个字符的UNICODE值
	        cp = Character.codePointAt(ach, i);
	        //判断这个字符的UNICODE值是不是EMOJI的UNICODE，如果是则取出对应的ID，如果不是则返回-1
	        int id=checkEmoji(cp);
	        //取该字符共占多少个字节
	        int count=Character.charCount(cp);
	        if (id!=-1){
	        	emoji = new EMOJI(i + begin, i + begin + count, id);
	        	emojis.add(emoji);
	        }
	        i += count;
	    }
	    return emojis;
	}
	
	/**
	 * 
	 * @n<b>函数名称</b>     :setImageSpannable
	 * @brief	对文本内的emoji表情替换图片
	 * @see
	 * @since    Ver 1.1
	 * @param  @param contentEdit
	 * @param  @param start	 需要替换的文本起始位置
	 * @param  @param count     需要替换的文本长度
	 * @param  @param type
	 * @return void
	 * @<b>作者</b>          :  huangszh
	 * @<b>创建时间</b>      :  2014-3-6下午2:24:25
	 */
	public void setImageSpannable(EditText contentEdit,int start,int count,int type){
		Editable editable = contentEdit.getText();
		String text = contentEdit.getText().toString();
		// 先查找是否有emoji表情
		ArrayList<EMOJI> emojis = seekEmojiArray(text.substring(start,start + count), start);
		int size = emojis.size();
		if(size == 0){
			return;
		}
		int drawSize = DisplayUtil.dip2px(
				ApplicationVariable.INSTANCE.applicationContext, Smiley.SIZE_STANDARD);
		Drawable drawable = null;
		Context context = ApplicationVariable.INSTANCE.applicationContext;
		EMOJI emoji;
		SmileyImageSpan span;
		// 有的话，遍历设置ImageSpan
		for(int i = 0; i < size; i++){
			emoji = emojis.get(i);
			drawable=getSmileyById(context, emoji.local_smiley_id);
			// 必须设置Bound，不然看不到。
			drawable.setBounds(0, 0, drawSize, drawSize);
			//必须加上source，为了复制时判断
			span = new SmileyImageSpan(drawable, 
					text.subSequence(emoji.start,emoji.end).toString(),
					ImageSpan.ALIGN_BOTTOM);
			editable.setSpan(span, emoji.start, emoji.end,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		}
	}
	
	/**
	 * 把一个表情添加到edittext里 
	 * <br>Created 2014-7-18 下午6:10:46
	 * @param id 表情的ID 
	 * @param drawable 表情的资源ID
	 * @param contentEdit 目标edittext
	 * @param type 表情的类型（Smiley.TYPE_WEIBO|Smiley.TYPE_CHAT)
	 * @param maxLength 最大长度
	 * @author       cb
	*/
	public void setSpannableToEditText(int id, Drawable drawable, EditText contentEdit,
			int type,int maxLength,int smileyDrawableSize) {
		Editable editable = contentEdit.getText();
		int selectionStart = contentEdit.getSelectionStart();
		SmileyImageSpan span;
		String insertStr = "";
		String imgStart = Smiley.getStartString(type);
		String imgEnd = Smiley.getEndString(type);
		Smiley smiley = Smileyhelper.getInstance().getSmiley(id);
		String smileyCode;
		//在微博里用的表情是[tip],聊天里用的是&<img>id<img>&
		if (type==Smiley.TYPE_CHAT){
			smileyCode=id+"";
		}else{
			smileyCode=smiley.tip;
		}
		insertStr=imgStart+smileyCode+imgEnd;
		if(maxLength > 0){
			if(contentEdit.getEditableText().toString().length() + insertStr.length() > maxLength){
				return;
			}
		}
		editable.insert(selectionStart,insertStr);
		//必须加上source，为了复制时判断
		span = new SmileyImageSpan(drawable, editable.subSequence(selectionStart,
				selectionStart + insertStr.length()).toString(),
				ImageSpan.ALIGN_BOTTOM);
		int size=0;
		if (smileyDrawableSize>0){
			size = DisplayUtil.dip2px(ApplicationVariable.INSTANCE.applicationContext,
					smileyDrawableSize);
		}else{
			size = DisplayUtil.dip2px(ApplicationVariable.INSTANCE.applicationContext,
					Smiley.SIZE_STANDARD);
		}
		
		drawable.setBounds(0, 0, size, size);

		editable.setSpan(span, selectionStart,
				selectionStart + insertStr.length(),
				Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

		contentEdit.setSelection(selectionStart + insertStr.length());
		contentEdit.requestFocus();
	}
	
	public SpannableString getSmileySpannableString(String text,int type){
		return getSmileySpannableString(text, type, Smiley.SIZE_STANDARD);
	}
	
	/**
	 * @n<b>函数名称</b>     :getSmileySpannableString
	 * @brief　把字符串里的表情用ImgSpan来显示到文本控件里
	 * @see
	 * @since    Ver 1.2
	 * @param  @param text  源文本
	 * @param  @param type　表情的类型（Smiley.TYPE_WEIBO|Smiley.TYPE_CHAT)
	 * @param  @param drawableSize　显示的表情图标的大小
	 * @param  @return
	 * @return SpannableString
	 * @<b>作者</b> : cb
	 * @<b>创建时间</b> : 2013-10-29下午2:01:15
	 */
	public SpannableString getSmileySpannableString(String text, int type,
			int drawableSize) {
		Context context = ApplicationVariable.INSTANCE.applicationContext;
		int index = 0;
		Drawable drawable;
		SmileyImageSpan span;
		text = seekEmoji(text, type);
		String imgStart = Smiley.getStartString(type);// 表情起始字符 
		String imgEnd = Smiley.getEndString(type); // 表情结束字符
		text = filterNoResourceSmiley(context, text, type);
		SpannableString spannable = new SpannableString(text);
		int start = text.indexOf(imgStart,index); // 找到第一个表情起始
		if(start == -1){
			return spannable; // 找不到，下面就不用做了
		}
		int end = text.indexOf(imgEnd, start + 1); 
		if(end == -1){
			return spannable; // 找不到，下面就不用做了
		}
		try {
			while (start < end) {
				// 取最近的匹配
				int offset = text.substring(start, end).lastIndexOf(imgStart);
				if(offset != 0){
					start += offset;
				}
				// 找到匹配到的内容，过滤前后
				String smileyIdStr = text.substring(start + imgStart.length(),end);
				// 拿着去查找id
				int id = getIdBySmileyStr(smileyIdStr);
				int drawSize = drawableSize;
				if (id!=Smileyhelper.NOT_FOUND) {
					drawable=getSmileyById(context, id);
					drawSize = DisplayUtil.dip2px(
								ApplicationVariable.INSTANCE.applicationContext, drawSize);
					if (drawable!=null){
						drawable.setBounds(0, 0, drawSize, drawSize);
						//必须加上source，为了复制时判断
						span = new SmileyImageSpan(drawable, text.subSequence(start,
								end + imgEnd.length()).toString(),
								ImageSpan.ALIGN_BOTTOM);
						spannable.setSpan(span, start, end + imgEnd.length(),
								Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
					}
					index = end + imgEnd.length();
					start = text.indexOf(imgStart, index);
					if(start == -1){
						break;
					}
					end = text.indexOf(imgEnd, start + 1);
					if(end == -1){
						break;
					}
				} 
				// 找不到的话
				else {
					index = end + imgEnd.length(); // 找到或者找不到都要从已经匹配规则的字符串后面开始找
					start = text.indexOf(imgStart, index);
					if(start == -1){
						break;
					}
					end = text.indexOf(imgEnd, start + 1);
					if(end == -1){
						break;
					}
				}
			}
		} catch (StringIndexOutOfBoundsException e) {
			spannable = new SpannableString(text);
		}
		return spannable;
	}
	
	/**
	 * @n<b>函数名称</b>     :filterNoResourceSmiley
	 * @brief　过滤本地无资源的表情
	 * @see
	 * @since    Ver 1.2
	 * @param  @param context
	 * @param  @param text
	 * @param  @param type
	 * @param  @return
	 * @return String
	 * @<b>作者</b>          :  cb
	 * @<b>创建时间</b>      :  2013-10-29下午2:00:37      
	*/
	public String filterNoResourceSmiley(Context context,String text,int type){
		int index=0;
		int start =0;
		int end=0;
		String imgStart=Smiley.getStartString(type);
		String imgEnd=Smiley.getEndString(type);
		StringBuffer str = new StringBuffer(text);
		StringBuffer temp = new StringBuffer();
		
		start = str.indexOf(imgStart,index);
		end = str.indexOf(imgEnd, index);
		
		try {
			while (start != -1 && end != -1 && start < end) {
				String smileyIdStr = str.substring(start + imgStart.length(),
						end);
				int id = getIdBySmileyStr(smileyIdStr);
				Smiley smiley = getSmiley(id);
				if (index != start) {
					temp.append(str.substring(index, start));
				}
				if (smiley == null) {
					// 未找到表情
					temp.append("[" + smileyIdStr + "]");
				} else {
					Bitmap bmp=getImageFromAssetsFile(context, smiley.name);
					if (bmp !=null ) {
						// 存在资源图片
						temp.append(imgStart + smileyIdStr + imgEnd);
						bmp.recycle();
					} else {
						temp.append("[" + smiley.tip + "]");
					}
				}
				index = end + imgEnd.length();
				start = str.indexOf(imgStart, index);
				end = str.indexOf(imgEnd, index);
			}
		} catch (StringIndexOutOfBoundsException e) {
			return text;
		}
		if (index != str.length()) {
			temp.append(str.substring(index, str.length()));
		}
		return temp.toString();
	}
	
	/**
	 * @n<b>函数名称</b>     :getIdBySmileyStr
	 * @brief 根据字符串获取对应的表情ID
	 * @see
	 * @since    Ver 1.2
	 * @param  @param smileyStr　目标串，可能是一个整数型的ID，也可能是一个TIP
	 * @param  @return
	 * @return int
	 * @<b>作者</b>          :  cb
	 * @<b>创建时间</b>      :  2013-10-29下午2:00:06      
	*/
	private int getIdBySmileyStr(String smileyStr){
		if (StringUtils.isNumeric(smileyStr)){
			try {
				return (Integer.parseInt(smileyStr));	
			} catch (NumberFormatException e) {
				return NOT_FOUND;
			}
			
		}else{
			if (TextUtils.isEmpty(smileyStr)){
				return NOT_FOUND;
			}
			return getSmileyIdByTip(smileyStr);
		}
	}
	
	/**
	 * @n<b>函数名称</b>     :delSmileyFromEdittext
	 * @brief　从edittext里面删除一个表情
	 * @see
	 * @since    Ver 1.2
	 * @param  @param editText　目标EDITTEXT
	 * @param  @param start　光标所在位置
	 * @param  @param type　表情的类型（Smiley.TYPE_WEIBO|Smiley.TYPE_CHAT)
	 * @param  @return
	 * @return int
	 * @<b>作者</b>          :  cb
	 * @<b>创建时间</b>      :  2013-10-29下午1:58:52      
	*/
	public int delSmileyFromEdittext(EditText editText,int start,int type){
		if (editText.getText()==null){
			return -1;
		}
		String smileyEndFlag="";
		String smileyStartFlag="";
		String flagText="";
		String editString=editText.getText().toString();
		if (type==Smiley.TYPE_CHAT){
			if (editString.length()<Smiley.IMGEND.length()+Smiley.IMGSTART.length()+1){
				//不可能是表情
				return -1;
			}
			smileyEndFlag=Smiley.IMGEND;
			smileyStartFlag=Smiley.IMGSTART;
			
		}else{
			if (editString.length()<Smiley.WEIBO_IMGEND.length()+Smiley.WEIBO_IMGSTART.length()+1){
				//不可能是表情
				return -1;
			}
			smileyEndFlag=Smiley.WEIBO_IMGEND;
			smileyStartFlag=Smiley.WEIBO_IMGSTART;
		}
		flagText=smileyEndFlag.substring(smileyEndFlag.length()-1);
		String subText=editString.substring(0, start);
		String lastText=subText.substring(start-1, start);
		int smileyStartIndex=subText.lastIndexOf(smileyStartFlag);
		int smileyEndIndex=subText.lastIndexOf(smileyEndFlag);
		if (lastText.equals(flagText)){
			//要删除的字符和表情的后缀的最后一个字符相同
			if (smileyEndIndex>-1 && smileyStartIndex>-1 && smileyEndIndex>smileyStartIndex && smileyEndFlag.length()+smileyEndIndex==start){
				//存在一个匹配的表情
				return smileyStartIndex;
			}
		}
		return -1;
	}
	
	//把形如&<img>0<img>&这样的表情表示字符换成[开心]这种形式
	public String showSmileyByTip(String srcStr,int type){
		if (TextUtils.isEmpty(srcStr)){
			return srcStr;
		}
		String imgStart=Smiley.getStartString(type);
		String imgEnd=Smiley.getEndString(type);
		StringBuffer temp=new StringBuffer();
		String src=seekEmoji(srcStr,type);       //将字符串中含有的emoji表情转化为形如&<img>0<img>&这样的表情表示字符
		String[] slices=src.split(imgStart);
		 try {
		int len=slices.length;
		
		if(len<=1){
			return src;
		}
		temp.append(slices[0]);
		for (int i=1;i<len;i=i+1){
				String slice=slices[i];
				int index=slice.indexOf(imgEnd);
				if(index<=0){
					//未匹配到结束标识或者未带ID(即&<img><img>&这样，中间没有ID)
					temp.append(imgStart);
					temp.append(slice);
					continue;
				}
				String smileyStr=slice.substring(0,index);
				int id=getIdBySmileyStr(smileyStr);
				Smiley smiley=getSmiley(id);
				if (smiley!=null){
					//找到对应的smiley
					temp.append("[");
					temp.append(smiley.tip);
					temp.append("]");
					temp.append(slice.substring(index+imgEnd.length()));
				}else{
					temp.append(imgStart);
					temp.append(slice);
				}
		}
		
		return temp.toString();
	} catch (Exception e) {
		return srcStr;
	}
	}
	
	/**
	 * @n<b>函数名称</b>     :valueToEmoji
	 * @brief 把字符串中含有emoji的形如&<img>0<img>&这样的表示字符串，转成实际的emoji表情
	 * @see
	 * @since    Ver 1.3
	 * @param  @param strSrc　源字符串
	 * @param  @return 
	 * @return 带实际emoji表情的字符串
	 * @<b>作者</b>          :  lsj
	 * @<b>创建时间</b>      :  2014-01-02上午11:00:00      
	*/
	public String getEmojiToSend(String srcStr) {		
		if (TextUtils.isEmpty(srcStr)) {
			return srcStr;
		}
		String IMG_START_FLAG = Smiley.getStartString(Smiley.TYPE_CHAT);
		String IMG_END_FLAG = Smiley.getEndString(Smiley.TYPE_CHAT);
		
		final Pattern EMOJI_PATTERN = Pattern
				.compile(IMG_START_FLAG + "([1-9]\\d*|0)" + IMG_END_FLAG);
		
		StringBuffer sbTemp = new StringBuffer();
		String strTemp = new String(srcStr);
		
		Matcher m = EMOJI_PATTERN.matcher(strTemp);
		try{
			while (m.find()) {
				// 判断是不是emoji表情
				String strEmoji = valueToEmoji(strTemp.substring(
						m.start() + IMG_START_FLAG.length(),
						m.end() - IMG_END_FLAG.length()));
				if(TextUtils.isEmpty(strEmoji)){
					//不是emoji表情，将这部分文字原样添加进temp
					sbTemp.append(strTemp.substring(0, m.end()));				
				}else{
					//是emoji表情，加入表情前文字，再加入emoji表情
					sbTemp.append(strTemp.substring(0, m.start()));
					sbTemp.append(strEmoji);
				}
				
				strTemp = strTemp.substring(m.end());
				m = EMOJI_PATTERN.matcher(strTemp);
			}
		}catch(IndexOutOfBoundsException e){
			return srcStr;
		}
		
		sbTemp.append(strTemp);
		return sbTemp.toString();
	}
	
	/**
	 * @n<b>函数名称</b>     :valueToEmoji
	 * @brief 根据&<img>0<img>&中间的数值，得到实际的emoji表情
	 * @see
	 * @since    Ver 1.3
	 * @param  @param strSrc　非负整数值
	 * @param  @return 
	 * @return 实际的emoji内容字符串，不是emoji时，返回""
	 * @<b>作者</b>          :  lsj
	 * @<b>创建时间</b>      :  2014-01-02上午11:07:06      
	*/
	private String valueToEmoji(String strValue){
		// 判断是不是emoji表情
		int id = getIdBySmileyStr(strValue);
		if (!Smileyhelper.getInstance().isEmoji(id)) {
			return "";
		}		
		
		// 是emoji则转成emoji
		Smiley smiley = getSmiley(id);
		if (smiley != null) {
			String hexcode = smiley.utf8Code;
			try {
				return new String(StringUtils.hexStringToBytes(hexcode),
						"utf-8");
			} catch (UnsupportedEncodingException e) {
			}
		}
		
		return "";
	}
	
	class MyUrlSpan extends URLSpan {
		public MyUrlSpan(String src) {
			super(src);
		}

		@Override
		public void onClick(View widget) {
			Context context = widget.getContext();
			String url = getURL();
			if (mIsOpenSysBrowser) {
				Uri uri = Uri.parse(url);
				Intent it = new Intent(Intent.ACTION_VIEW, uri);
				context.startActivity(it);
			} else {
				Intent intent = new Intent();
				intent.setClassName(context,
						"com.product.android.ui.activity.WebViewActivity");
				intent.putExtra(Browser.EXTRA_APPLICATION_ID,
						context.getPackageName());
				intent.putExtra("extars_webview_url", url);
				context.startActivity(intent);
			}
			widget.setPressed(false);
			widget.setSelected(false);
		}
	}

	//FRI HYK修改 by明星App
	/**
	 * 设置打开URL是打开App自带的还是请求系统的
	 * 
	 * <br>
	 * Created 2014-8-18 下午4:49:16
	 * 
	 * @param isOpenSysBrowser
	 *            打开URL是打开App自带的还是系统默认的，true：请求系统的浏览器，false：打开App自带的
	 * @author : HuangYK
	 */
	public void setIsOpenSysBrowser(boolean isOpenSysBrowser) {
        Log.e("HYK","setIsOpenSysBrowser = " + isOpenSysBrowser);
        mIsOpenSysBrowser = isOpenSysBrowser;
	}
	
	/**
     * @n<b>函数名称</b> :delSmileyFromString
     * @brief　从String里面删除一个表情
     * <br>Created 2014-8-18 下午5:52:21
     * @param editString 目标String
     * @param start 　光标所在位置
     * @param type 表情的类型（Smiley.TYPE_WEIBO|Smiley.TYPE_CHAT)
     * @return int 删除的位置，-1表示不是以表情结尾的情况
     * @author       wangds
     */
    public int delSmileyFromString(String editString, int start, int type) {
        if (TextUtils.isEmpty(editString)) {
            return -1;
        }
        String smileyEndFlag = "";
        String smileyStartFlag = "";
        String flagText = "";
        if (type == Smiley.TYPE_CHAT) {
            if (editString.length() < Smiley.IMGEND.length() + Smiley.IMGSTART.length() + 1) {
                // 不可能是表情
                return -1;
            }
            smileyEndFlag = Smiley.IMGEND;
            smileyStartFlag = Smiley.IMGSTART;

        } else {
            if (editString.length() < Smiley.WEIBO_IMGEND.length() + Smiley.WEIBO_IMGSTART.length()
                    + 1) {
                // 不可能是表情
                return -1;
            }
            smileyEndFlag = Smiley.WEIBO_IMGEND;
            smileyStartFlag = Smiley.WEIBO_IMGSTART;
        }
        flagText = smileyEndFlag.substring(smileyEndFlag.length() - 1);
        String subText = editString.substring(0, start);
        String lastText = subText.substring(start - 1, start);
        int smileyStartIndex = subText.lastIndexOf(smileyStartFlag);
        int smileyEndIndex = subText.lastIndexOf(smileyEndFlag);
        if (lastText.equals(flagText)) {
            // 要删除的字符和表情的后缀的最后一个字符相同
            if (smileyEndIndex > -1 && smileyStartIndex > -1 && smileyEndIndex > smileyStartIndex
                    && smileyEndFlag.length() + smileyEndIndex == start) {
                // 存在一个匹配的表情
                return smileyStartIndex;
            }
        }
        return -1;
    }
}